const crypto = require('crypto'); 

// 拼多多 Client ID
const pin_client_id = 'e6750fe2ad4743119d00a3578b146030'
// 拼多多 Client Secret
const pin_client_secret = '097abfc402d532286b07461aa85a04cd17900c27'


// 生成md5
function md5(data){
  // 以md5的格式创建一个哈希值
  var crypto=require('crypto');
  var md5=crypto.createHash("md5");
  md5.update(data);
  var str=md5.digest('hex');
  return str

}

// 生成拼多多公共请求参数
function commonQuery(query) {
	
	let timestamp = Date.now() / 1000
	timestamp = parseInt(timestamp)
	
	let params = {
		'client_id':pin_client_id,
		'data_type':'JSON',
		'timestamp':timestamp,
	}
	params = {...params, ...query}
	// console.log('params', params)
	
	  let sorted = Object.keys(params).sort()
	  let basestring = pin_client_secret
	  for (let i = 0, l = sorted.length; i < l; i++) {
	    let k = sorted[i]
	    basestring += k + params[k]
	  }
	  basestring += pin_client_secret
	  params.sign = md5(basestring).toUpperCase()
	
	return params
}

module.exports = {
	commonQuery
}